package rsj.service;

import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.TableNode;
import com.rlyy.aibase.utils.helpers.JsonHelper;
import common.util.Assert;
import common.util.BaseZtree.BaseZTree;
import common.util.BaseZtree.BaseZtreeUtils;
import rsj.context.ApplicationContextUtil;
import rsj.dao.MenuInfoDao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MenuInfoService {


    private static final MenuInfoService infoService = new MenuInfoService();

    public static MenuInfoService getInstance() {
        return infoService;
    }

    private static MenuInfoDao infoDao = MenuInfoDao.getInstance();

    public MapNode findMenuForRole(Connection conn, MapNode data) throws SQLException {


        String userId = data.getValue("User_Id");
        //Assert.isNotBlank(userId, "User_Id不能为空");

        TableNode tNode = infoDao.findAllMenu(conn, userId);
        List<BaseZTree> queryList = new ArrayList<>();

        for (int i = 0; i < tNode.length(); i++) {
            MapNode map = tNode.getMapNode(i);
            BaseZTree tree = new BaseZTree(map.getValue("Menu_Id"), map.getValue("Menu_Title"), map.getValue("Menu_Pid"));
            queryList.add(tree);
        }
        List<BaseZTree> templeList = BaseZtreeUtils.getTemplateData(queryList);

        MapNode responsedata = new MapNode();
        responsedata.putNode("Menu_List", JsonHelper.list2Json(templeList));

        return responsedata;

    }

    public MapNode findMenuAuth(Connection conn, MapNode data) throws SQLException {


        String userId = data.getValue("User_Id");
        Assert.isNotBlank(userId, "User_Id不能为空");

        TableNode map = infoDao.findMenuAuth(conn, userId);

        MapNode responsedata = new MapNode();
        responsedata.putNode("Menu_List", map.toJson());
        CacheMenuService cacheMenuService = ApplicationContextUtil.getBean(CacheMenuService.class);
        cacheMenuService.asyncSaveMenuToRedis(map, userId);
        return responsedata;

    }

}
